package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.RequisitionDetail;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.MultiLinesViewNew;
import com.isunland.managesystem.widget.SingleLineViewNew;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

public class CheckTripFragment extends CheckDetailFragment {
  protected static final int REQUEST_PLAN_DATE_START = 0;
  protected static final int REQUEST_PLAN_DATE_END = 3;
  protected static final int REQUEST_ACTUAL_DATE_END = 1;
  protected static final int REQUEST_ACTUAL_DATE_START = 2;
  public static final int REQUEST_DELETE = 6;
  public static final int REQUEST_SUBMIT = 7;

  private MultiLinesViewNew mEtReason;
  private SingleLineViewNew mTvActualStartTime;
  private SingleLineViewNew mTvActualEndTime;
  private SingleLineViewNew mEtNautralDays;
  private EditText mEtFrom;
  private EditText mEtTo;

  private RadioButton mRbApplyTrip; //申请
  private RadioButton mRbSupplyTrip;//补填
  //private TextView mtvStartTimeTrip;//开始时间
  //private TextView mtvEndTimeTrip;//结束时间
  private String mIfLaterWriter = "0";//是申请还是补填

  /**
   * Find the Views in the layout<br />
   * <br />
   * Auto-created on 2015-12-10 12:17:30 by Android Layout Finder
   * (http://www.buzzingandroid.com/tools/android-layout-finder)
   */
  private void findViews(View v) {

    mEtFrom = (EditText) v.findViewById(R.id.et_from_checkTrip);
    mEtTo = (EditText) v.findViewById(R.id.et_to_checkTrip);
    mEtReason = (MultiLinesViewNew) v.findViewById(R.id.et_overTimeReason_checkOver);
    mTvActualStartTime = (SingleLineViewNew) v.findViewById(R.id.tv_actualBeginTime_checkOver);
    mTvActualEndTime = (SingleLineViewNew) v.findViewById(R.id.tv_actualEndTime_checkOver);
    mEtNautralDays = (SingleLineViewNew) v.findViewById(R.id.et_naturalTripDays_checkTrip);

    RadioGroup mRgTripType = (RadioGroup) v.findViewById(R.id.rg_type);
    mRbApplyTrip = (RadioButton) v.findViewById(R.id.rb_apply);
    mRbSupplyTrip = (RadioButton) v.findViewById(R.id.rb_supply);

    //mtvStartTimeTrip = (TextView) v.findViewById(R.id.tv_startTime_trip);
    //mtvEndTimeTrip = (TextView) v.findViewById(R.id.tv_endTime_trip);

    mTvActualStartTime.getTvContent().setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {

        showDialog(mTvActualStartTime.getTvContent().getText().toString().trim(),
            R.string.chooseTime,
            REQUEST_ACTUAL_DATE_START);
      }
    });
    mTvActualEndTime.getTvContent().setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {

        showDialog(mTvActualEndTime.getTvContent().getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE_END);
      }
    });

    if (mMenuType == CHECK_PASS || mMenuType == WAIT_CHECK) {

      mEtReason.getTvContent().setEnabled(false);
      mTvActualStartTime.getTvContent().setEnabled(false);
      mTvActualEndTime.getTvContent().setEnabled(false);
      mEtNautralDays.getTvContent().setEnabled(false);
      mRbApplyTrip.setEnabled(false);
      mRbSupplyTrip.setEnabled(false);
      mEtFrom.setEnabled(false);
      mEtTo.setEnabled(false);
    }
    if (mMenuType == TODO) {
      //待办流程确认时间,只可编辑时间
      mEtReason.getTvContent().setEnabled(false);
      mRbApplyTrip.setEnabled(false);
      mRbSupplyTrip.setEnabled(false);
      mEtFrom.setEnabled(false);
      mEtTo.setEnabled(false);
    }
    mRgTripType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
          case R.id.rb_apply:
            mIfLaterWriter = "0";
            break;
          case R.id.rb_supply:
            mIfLaterWriter = "1";
            break;

          default:
            break;
        }
        initRadio(mIfLaterWriter);
      }
    });
  }

  private void initRadio(String ifLaterWriter) {
    if ("0".equalsIgnoreCase(ifLaterWriter)) {
      mTvActualStartTime.getTvTitle().setText(R.string.planBeginTime);
      mTvActualEndTime.getTvTitle().setText(R.string.planEndTime);
      mTvActualStartTime.getTvContent().setHint(R.string.planBeginTimeHint);
      mTvActualEndTime.getTvContent().setHint(R.string.planEndTimeHint);
    }
    if ("1".equalsIgnoreCase(ifLaterWriter)) {
      mTvActualStartTime.getTvTitle().setText(R.string.actualBeginTime);
      mTvActualEndTime.getTvTitle().setText(R.string.actualEndTime);
      mTvActualStartTime.getTvContent().setHint(R.string.actualBeginTimeHint);
      mTvActualEndTime.getTvContent().setHint(R.string.actualEndTimeHint);
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    setTitleCustom(R.string.requisitiontrip);// 1.更改标题.
    View view = inflater.inflate(R.layout.fragment_check_trip, container, false);
    findViews(view);
    laterViewVisiblity(view, ifAllowSupplement);
    initDetailData();

    return view;
  }

  private void initDetailData() {
    mEtNautralDays.getTvContent().setText("0.0");
    if (mMenuType != ADD) {
      volleypostInit();
    }
  }

  private void volleypostInit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DETAIL);
    HashMap<String, String> params = new HashMap<>();
    params.put("attendType", mType);
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String response) {

        MyUtils.dismissDialog();
        try {
          RequisitionDetail requisitionDetail =
              new Gson().fromJson(response, RequisitionDetail.class);
          mEtFrom.setText(requisitionDetail.getFromArea());
          mEtTo.setText(requisitionDetail.getToArea());
          mEtReason.getTvContent().setText(requisitionDetail.getBtripReason());// 3.获取差旅原因.
          mTvActualStartTime.getTvContent().setText(requisitionDetail.getActSTime());
          mTvActualEndTime.getTvContent().setText(requisitionDetail.getActETime());
          mIfLaterWriter = requisitionDetail.getBtripType();
          if ("1".equalsIgnoreCase(mIfLaterWriter)) {
            mRbSupplyTrip.setChecked(true);
          }
          if ("0".equalsIgnoreCase(mIfLaterWriter)) {
            mRbApplyTrip.setChecked(true);
          }
          initRadio(mIfLaterWriter);
          mEtNautralDays.getTvContent().setText(requisitionDetail.getNaturalDays());// 5.自然天数..
        } catch (JsonSyntaxException e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.wrong_data);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
        ToastUtil.show(R.string.noConnectionToServer);
      }
    });
  }

  private void showDialog(String startDate, int titleId, int requestCode) {
    Date date = DateUtil.stringToDate(startDate);
    if (null == date) {
      date = new Date();
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    DialogFragment dialog = BaseTimeDialogFragment.newInstance(date, titleId);
    dialog.setTargetFragment(CheckTripFragment.this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;
    String startDate;// 开始时间
    String endDate;// 结束时间

    // 更新

    if (requestCode == REQUEST_ACTUAL_DATE_START) {

      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualStartTime.getTvContent().setText(dateString);
      startDate = mTvActualStartTime.getTvContent().getText().toString().trim();
      endDate = mTvActualEndTime.getTvContent().getText().toString().trim();
      // 获取工时
      // getWorkHours(requestCode, startDate, endDate);

      // 2.计算差旅自然日.
      getTripNautralDays(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_ACTUAL_DATE_END) {

      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualEndTime.getTvContent().setText(dateString);
      startDate = mTvActualStartTime.getTvContent().getText().toString().trim();
      endDate = mTvActualEndTime.getTvContent().getText().toString().trim();
      // 2.计算差旅自然日.
      getTripNautralDays(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      volleyPostSave(TYPE_RUN);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   * 后台计算差旅自然日天数.
   */
  private void getTripNautralDays(int requestCode, String startTime, String endTime) {
    if (TextUtils.isEmpty(startTime) || TextUtils.isEmpty(endTime)) {
      return;
    }
    if (DateUtil.before(endTime, startTime)) {
      return;
    }

    // 如果是计划时间变化,实际开始时间,结束时间都不为空.此时不赋值差旅自然天数.
    if (requestCode == REQUEST_PLAN_DATE_END || requestCode == REQUEST_PLAN_DATE_START) {
      String actualSTime = mTvActualStartTime.getTvContent().getText().toString().trim();
      String actualETime = mTvActualEndTime.getTvContent().getText().toString().trim();
      if ((!TextUtils.isEmpty(actualSTime)) && (!TextUtils.isEmpty(actualETime))) {
        return;
      }
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_TRIP_NAUTRALHOUR);
    HashMap<String, String> params = new HashMap<>();
    params.put("sTime", startTime);
    params.put("eTime", endTime);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingTripDays);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {
        MyUtils.dismissDialog();
        try {
          SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
          if (SuccessMessage.SUCCESS.equals(message.getResult())) {
            String days = message.getMessage();
            mEtNautralDays.getTvContent().setText(days);
          }
          if (SuccessMessage.FAILURE.equals(message.getResult())) {
            mEtNautralDays.getTvContent().setText("0.0");
            ToastUtil.show(message.getMessage());
          }
        } catch (Exception e) {
          LogUtil.e("nautralDay", e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
      }
    });
  }

  // private void getWorkHours(final int requestCode, String startTime, String
  // endTime) {
  //
  // if (TextUtils.isEmpty(startTime) || TextUtils.isEmpty(endTime)) {
  // return;
  //
  // }
  // if (DateUtil.before(endTime, startTime)) {
  // return;
  // }
  // String url =
  // ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_TRIP_WORKHOUR);
  // HashMap<String, String> params = new HashMap<String, String>();
  // String jobNumber = CurrentUser.newInstance(getActivity()).getJobNumber();
  // params.put("jobno", jobNumber);// 6.计算差旅天数.
  // params.put("startDate", startTime);
  // params.put("endDate", endTime);
  // params.put("ifOneDay", "true");
  // MyUtils.showDialogLoading(getActivity(), R.string.loadingWorkHour);
  // mActivity.volleyPost(url, params, new VolleyResponse() {
  //
  // @Override
  // public void onVolleyResponse(String arg0) {
  // MyUtils.dismissDialog();
  // try {
  // WorkHour workHour = new Gson().fromJson(arg0, WorkHour.class);
  // if (workHour.getResult() == 1) {
  // String days = workHour.getMessage().getDays() + "";// 6.计算差旅天数.
  // String hours = workHour.getMessage().getHours() + "";
  //
  // if (requestCode == REQUEST_PLAN_DATE_START || requestCode ==
  // REQUEST_PLAN_DATE_END) {
  //
  // mEtPlanDays.setText(days);
  // }
  // if (requestCode == REQUEST_ACTUAL_DATE_START || requestCode ==
  // REQUEST_ACTUAL_DATE_END) {
  //
  // mEtActualDays.setText(days);
  // }
  //
  // }
  //
  // } catch (Exception e) {
  // LogUtil.e("workTimeOverError=" + e, e);
  // }
  //
  // }
  //
  // @Override
  // public void onVolleyError(VolleyError arg0) {
  // MyUtils.dismissDialog();
  //
  // }
  // });
  //
  // }

  @Override public boolean isCorrectInput() {
    // 验证文本信息
    String reasonString = mEtReason.getTvContent().getText().toString().trim();
    //String currentTime = DateUtil.dateToString(new Date());// 当前时间
    String planBeginTime = mTvActualStartTime.getTvContent().getText().toString().trim();
    String planEndTime = mTvActualEndTime.getTvContent().getText().toString().trim();
    String actualBeginTime = mTvActualStartTime.getTvContent().getText().toString().trim();
    String actualEndTime = mTvActualEndTime.getTvContent().getText().toString().trim();
    // String planHours = mEtPlanDays.getText().toString().trim();
    if (TextUtils.isEmpty(reasonString)) {
      ToastUtil.show(R.string.no_content);
      return false;
    }

    if ("0".equalsIgnoreCase(mIfLaterWriter)) {
      if (TextUtils.isEmpty(planBeginTime)) {
        ToastUtil.show(R.string.chooseStartTime);
        return false;
      }
      if (TextUtils.isEmpty(planEndTime)) {
        ToastUtil.show(R.string.chooseEndTime);
        return false;
      }
      boolean flag = DateUtil.before(planBeginTime, planEndTime);
      if (!flag) {
        ToastUtil.show(R.string.realEndTimeAfterRealStartTime);
        return false;
      }
    }

    if ("1".equalsIgnoreCase(mIfLaterWriter)) {
      if (TextUtils.isEmpty(actualBeginTime)) {
        ToastUtil.show(R.string.chooseRealStartTime);
        return false;
      }
      if (TextUtils.isEmpty(actualEndTime)) {
        ToastUtil.show(R.string.chooseRealEndTime);
        return false;
      }
      //            if (!DateUtil.before(actualBeginTime, currentTime)) {
      //                ToastUtil.show("实际开始时间不能大于当前时间");
      //                return false;
      //            }
      //
      //            if (!DateUtil.before(actualEndTime, currentTime)) {
      //                ToastUtil.show("实际结束时间不能大于当前时间");
      //                return false;
      //            }

      if (!DateUtil.before(actualBeginTime, actualEndTime)) {
        ToastUtil.show(R.string.realEndTimeAfterRealStartTime);
        return false;
      }
    }

    // if (TextUtils.isEmpty(planHours)) {
    // Toast.makeText(getActivity(), "计划工时不能为空", Toast.LENGTH_SHORT).show();
    // return false;
    // }
    // if ("0.0".equalsIgnoreCase(planHours) ||
    // "0".equalsIgnoreCase(planHours)) {
    // Toast.makeText(getActivity(), "计划工时不能为0", Toast.LENGTH_SHORT).show();
    // return false;
    // }
    return true;
  }

  @Override protected void volleyPostSave(final String type) {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_SAVE_OR_RUN);

    ParamsNotEmpty params = new ParamsNotEmpty();

    params.put("attendType", CheckDetailFragment.VALUE_TRIP);
    params.put("saveOrRun", type);
    params.put("btripReason", mEtReason.getTvContent().getText().toString().trim());
    params.put("fromArea", mEtFrom.getText().toString().trim());
    params.put("toArea", mEtTo.getText().toString().trim());

    //        if(mRbSupplyTrip.isChecked()) {
    params.put("planSTime", mTvActualStartTime.getTvContent().getText().toString().trim());
    params.put("planETime", mTvActualEndTime.getTvContent().getText().toString().trim());
    /**是否补填*/

    params.put("btripType", mIfLaterWriter);

    params.put("actSTime", mTvActualStartTime.getTvContent().getText().toString().trim());
    params.put("actETime", mTvActualEndTime.getTvContent().getText().toString().trim());

    String natualDays = mEtNautralDays.getTvContent().getText().toString().trim();
    if (TextUtils.isEmpty(natualDays)) {
      natualDays = "0.0";
    }
    params.put("naturalDays", natualDays);
    if (mMenuType == TODO) {
      //待办流程中修改差旅单
      params.put("isFlow", "true");
    }
    if (mMenuType != ADD) {
      params.put("id", mId);
      if (TYPE_RUN.equals(type)) {

        params.put("isList", "0");
        params.put("dataStatus", "waitCheck");
      }
    }
    /**不传*/
    //         if ("abort".equalsIgnoreCase(mDataStatus)) {
    //         params.put("dataStatus", "new");
    //         }
    LogUtil.i("差旅params===" + params.toString());
    if (TYPE_RUN.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    }
    if (TYPE_SAVE.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    }

    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          switch (successType) {
            case "1":
              getActivity().setResult(Activity.RESULT_OK);
              ToastUtil.show(R.string.success_operation);
              getActivity().finish();

              break;
            case "0":
              showErrorDialog(successsMessage.getMessage());
              break;
            default:
              ToastUtil.show(R.string.failure_operation);
              break;
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", mType + "#" + mId);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            getActivity().setResult(Activity.RESULT_OK);
            ToastUtil.show(R.string.success_operation);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }
}
